package com.sunfeng.chap5.selectkey;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 从通道中获取数据
 */
public class Test12 {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        serverSocketChannel.bind(new InetSocketAddress("localhost", 8888));
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();

        SelectionKey selectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        boolean isRun = true;
        while (isRun == true) {
            int keyCount = selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isAcceptable()) {
                }
                ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                ServerSocket serverSocket = channel.socket();

                Socket socket = serverSocket.accept();
                InputStream inputStream = socket.getInputStream();
                byte[] bytes = new byte[1024];
                int readLength = inputStream.read(bytes);
                while (readLength != -1) {
                    String s = new String(bytes, 0, readLength);
                    System.out.println(s);
                    readLength = inputStream.read(bytes);
                }
                inputStream.close();
                socket.close();
                iterator.remove();
            }
        }
        serverSocketChannel.close();

    }
}
